package main

import (
	"fmt"
	v1http "gitee.com/scottq/go-framework/src/v1/httpserver"
	v1log "gitee.com/scottq/go-framework/src/v1/log"
	"github.com/gin-gonic/gin"
	"net/http"
	"os"
	"path/filepath"
)

func main() {
	name := "example"
	logPath := fmt.Sprintf("./runtime/logs/%s.log", filepath.Base(os.Args[0]))

	logger := v1log.NewZapLog(name, logPath, nil)
	httpServer, err := v1http.NewHttpServer("", ":8080")
	if err != nil {
		logger.Error("run http server error:%s" + err.Error())
		return
	}
	//添加logger
	httpServer.AddLogger(logger)

	//注册简单的控制器
	httpServer.RouteGet("/v1", Index, nil)
	//自定义health
	httpServer.RouteGet(v1http.HealthUrl, Health, nil)

	//适配gin框架
	//两边注册路径必须一致
	engine := gin.New()
	engine.GET("/ginv1", gin.Recovery(), GinMiddleware, GinIndex)
	httpServer.RouteHandler(http.MethodGet, "/ginv1", engine, nil)

	logger.Fatal(httpServer.Run().Error())
}

//http router
func Index(ctx *v1http.Ctx) {
	ctx.Write([]byte("Hello"))
}

func Health(ctx *v1http.Ctx) {
	ctx.Write([]byte("SERVICE OK"))
}

//gin handler
func GinIndex(c *gin.Context) {
	c.JSON(http.StatusOK, map[string]interface{}{
		"data":   nil,
		"length": 1,
	})
}

func GinMiddleware(c *gin.Context) {
	if c.Query("stop") == "1" {
		c.String(http.StatusOK, "stop")
		c.Abort()
		return
	}
	c.Next()
}
